package com.kexio.core.web.config;

import com.kexio.core.properties.CoreProperties;
import java.util.Arrays;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * CORS跨域配置
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@Configuration
@EnableConfigurationProperties(CoreProperties.class)
@ConditionalOnProperty(prefix = "kexio.core.web.cors", name = "enabled", havingValue = "true", matchIfMissing = true)
public class CorsConfig {
    
    private static final Logger log = LoggerFactory.getLogger(CorsConfig.class);
    
    private final CoreProperties coreProperties;
    
    public CorsConfig(CoreProperties coreProperties) {
        this.coreProperties = coreProperties;
        log.info("==> Kexio CORS配置已启用");
    }
    
    @Bean
    public CorsFilter corsFilter() {
        CoreProperties.Web.Cors corsProps = coreProperties.getWeb().getCors();
        
        CorsConfiguration config = new CorsConfiguration();
        
        // 允许的源
        if (corsProps.getAllowedOrigins() != null) {
            config.setAllowedOriginPatterns(Arrays.asList(corsProps.getAllowedOrigins()));
        } else {
            config.setAllowedOriginPatterns(Collections.singletonList("*"));
        }
        
        // 允许的方法
        if (corsProps.getAllowedMethods() != null) {
            config.setAllowedMethods(Arrays.asList(corsProps.getAllowedMethods()));
        } else {
            config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        }
        
        // 允许的头
        if (corsProps.getAllowedHeaders() != null) {
            config.setAllowedHeaders(Arrays.asList(corsProps.getAllowedHeaders()));
        } else {
            config.addAllowedHeader("*");
        }
        
        // 是否允许凭证
        config.setAllowCredentials(corsProps.isAllowCredentials());
        
        // 预检请求的有效期，单位为秒
        config.setMaxAge(3600L);
        
        // 暴露的头信息
        config.setExposedHeaders(Arrays.asList(
            "Authorization", "Content-Type", "X-Requested-With", "Accept",
            "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers",
            "X-Total-Count", "X-Page-Count", "X-Current-Page"
        ));
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        
        log.debug("CORS配置详情: 允许源={}, 允许方法={}, 允许凭证={}", 
            Arrays.toString(corsProps.getAllowedOrigins()),
            Arrays.toString(corsProps.getAllowedMethods()),
            corsProps.isAllowCredentials()
        );
        
        return new CorsFilter(source);
    }
}
